﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;

namespace myProxy
{
    public class ProxyEndPointParser
    {
        private List<Regex> regexList;

        public ProxyEndPointParser()
        {
            regexList = new List<Regex>();
            regexList.Add(new Regex("(?<ip>.*?):(?<port>.*?)@"));
            regexList.Add(new Regex("\\w+\\s+(?<ip>.*?)\\s+(?<port>.*?)\\s+"));
            regexList.Add(new Regex("(?<ip>.*?)\\s+(?<port>\\d+?)\\s+"));
            regexList.Add(new Regex("(?<ip>.*?)\\s+(?<port>\\d+?)$"));
        }

        public IPEndPoint GetEndPoint(string str)
        {
            string strIp = "";
            string strPort = "";
            IPEndPoint ep = null;
            foreach (Regex r in regexList)
            {
                strIp = r.Match(str.TrimStart()).Groups["ip"].Value;

                strPort = r.Match(str).Groups["port"].Value;

                if ((strIp.Length >= 7 && strIp.Length <= 15) && (strPort.Length >= 2 && strPort.Length <= 5))
                {
                    break;
                }
            }

            //Debug.WriteLine("{0},{1}", strIp, strPort);

            if (strIp == "" || strPort == "")
                return null;

            try
            {
                IPAddress ipaddr = IPAddress.Parse(strIp);
                ep = new IPEndPoint(ipaddr, int.Parse(strPort));
            }
            catch
            {
                throw new ArgumentException();
            }

            return ep;
        }
    }
}